package com.googlecode.imanager.jasper;

import java.io.OutputStream;

import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRXlsExporter;

import com.googlecode.imanager.client.Application;
import com.googlecode.imanager.client.Document;
import com.googlecode.imanager.client.Manager;
import com.googlecode.imanager.client.bridge.BridgeType;
import com.googlecode.imanager.client.event.EvaluationPhase;
import com.googlecode.imanager.core.base.DefaultManager;

/**
 * @author wellsantos@wellsantos.com
 * @since 0.01
 */
public class XlsApplication extends RApplication {

    public XlsApplication(DefaultManager manager, Application application, OutputStream output) {
        super(manager, application, output);
    }

    @Override
    public BridgeType getImplementationType() {
        return BridgeType.XLS;
    }

    @Override
    public void generateBridgePrint(Document document) throws Exception {        
        firePhaseEvent(document, EvaluationPhase.DOCUMENT_START);
        document.setVisible(true);
        
        RDocument report = (RDocument) Manager.getImpl(document);
        report.lockDocument(true);
        try {
            XlsPageBuilder printer = new XlsPageBuilder(report, new JasperPrint());
            printer.buildSinglePage(true);
    
            // TODO fazer as alterações do evento DOCUMENT_END refletirem em todas as páginas
            firePhaseEvent(document, EvaluationPhase.DOCUMENT_END);
    
            JRXlsExporter exporter = new JRXlsExporter();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, printer.getPrint());
            exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, getOutput());
            
            //exporter.setParameter(JRXlsAbstractExporterParameter.IS_DETECT_CELL_TYPE, true);
            //exporter.setParameter(JRXlsAbstractExporterParameter.IS_WHITE_PAGE_BACKGROUND, true);
            
            exporter.exportReport();
            
        } finally {
            report.lockDocument(false);
        }
    }

}
